﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using TouchSocket.Core;

namespace LD.Host.项目
{
    public static class ScrewDB
    {
        public static string[] SlotIds { get; set; } = new string[4];
        public static string NewId
        {
            get
            {
                return Guid.NewGuid().ToString();
            }
        }
        public static void MainTable(short el, TB_ScrewData data, List<short> chn1, List<short> chn2)
        {
            #region 确保目录的存在
            string directoryPath = "D:\\ScrewData"; //目录路径

            // 确保目录存在
            Directory.CreateDirectory(directoryPath);
            #endregion

            int id = DBHelper.Instance.Sql.Insertable(data).ExecuteReturnIdentity();

            Acup_DB(el, id, chn1, chn2);

            ScrewActioToCSV(directoryPath, id, data.SN, data.Num);
        }
        private static void Screw_CSV(string barcode)
        {
            string directoryPath = "D:\\ScrewData";
            var screwList = DBHelper.Instance.Sql.Queryable<TB_ScrewData>()
                    .Where(p => p.SN == barcode && !p.IsCsv).OrderBy(p => p.Num).ToList();
            if (screwList.Count() > 0)
            {
                //csv
                var screwstring = new List<string>
                {
                    // 添加表头数据
                    "Order,ProductID,Task,Time,Rounds(r),Torque(Kgf.cm),TimeConsuming(ms),State,Alarm,Channel,Floating,SpeedMax,SpeedState,TorqueState"
                };

                //将所有对象中的字段拼接成csv样式
                screwstring.AddRange(screwList.Select(item => string.Join(",",
                                 item.Num,
                                 item.SN,
                                 item.TaskId,
                                 item.Time,
                                 item.Rounds,
                                 item.Torque,
                                 item.TimeConsuming,
                                 item.Result_State,
                                 item.Alarm_State,
                                 "BackY2",
                                 "0",
                                 item.SpeedFeedback,
                                 "Normal",
                                 item.Alarm_State
                             )));
                screwstring.Add(screwList.Where(p => p.Result_State == "NG")?.FirstOrDefault()?.Result_State == "NG" ? "Result,FAIL" : "Result,PASS");

                string csvString = string.Join(Environment.NewLine, screwstring);
                string filePath = Path.Combine(directoryPath, $"{barcode}.csv");

                File.WriteAllText(filePath, csvString, System.Text.Encoding.UTF8);
            }
        }
        private static void ScrewActioToCSV(string directoryPath, int pid, string barcode, int num)
        {
            try
            {
                //csv
                #region 总螺丝数据csv
                Screw_CSV(directoryPath);
                #endregion

                #region 单穴位csv
                Acup_CSV(directoryPath, pid, barcode, num);

                #endregion
            }
            catch (Exception ex)
            {
                Log4.Warr("Csv生产失败" + ex);
            }
        }
        private static void Acup_CSV(string directoryPath, int pid, string barcode, int num)
        {
            var chnList = DBHelper.Instance.Sql.Queryable<TB_ScrewDetailData>()
                   .Where(p => p.Pid == pid).ToList();

            if (chnList.Count() > 0)
            {
                var chn = new List<string>
                {
                    // 添加表头数据
                    "DeviceType,DPLUS-L-amazon",
                    $"CHN1,SpeedFeedback(rpm),{chnList.Max(p=>p.Chn1)}",
                    $"CHN2,Torque(Kgf.cm),{chnList.Max(p=>p.Chn2)}",
                    $"ReceivePoints,{chnList.Count}",
                    "SampleInterval,3",
                    "Time(ms),CHN1,CHN2"
                };
                //将所有对象中的字段拼接成csv样式
                chn.AddRange(chnList.Select(item => string.Join(",",
                               item.Times,
                               item.Chn1,
                               item.Chn2.ToString()
                           )));
                string filePath = Path.Combine(directoryPath, $"{barcode}_{num}.csv");
                string csvString = string.Join(Environment.NewLine, chn);
                File.WriteAllText(filePath, csvString, System.Text.Encoding.UTF8);
            }
        }
        private static void Acup_DB(short el, int pid, List<short> chn1, List<short> chn2)
        {
            var detail = new List<TB_ScrewDetailData>();
            int times = 0;
            for (int i = 0; i < chn2.Count; i++)
            {
                detail.Add(new TB_ScrewDetailData()
                {
                    Pid = pid,
                    Times = times,
                    Chn1 = chn1[i],
                    Chn2 = Math.Round(chn2[i] * 0.01, 3)
                }); ;
                times += Convert.ToInt32(el) / 1000;
            }
            //单穴位数据写入库中
            DBHelper.Instance.Sql.Insertable(detail).ExecuteCommand();
        }
    }

}
